package juc.flowcontrol.semaphore;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author fangbin
 * @desc
 * @date 2020/6/26 9:41
 */
public class SemaphoreDemo {
    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(3,true);
        ExecutorService executorService = Executors.newFixedThreadPool(100);

        for(int i=0;i<100;i++){
            executorService.submit(new Task(semaphore));
        }
    }
}

class Task implements Runnable{
    Semaphore semaphore;

    public Task(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public void run() {

        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName()+"获取资源");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"释放资源");
        semaphore.release();
    }
}
